package com.ruoyi.oar.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.oar.domain.dto.OarCheckInRecordDTO;
import com.ruoyi.oar.domain.query.OarCheckInRecordQuery;
import com.ruoyi.oar.service.OarCheckInRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 租客入住记录Controller
 *
 * @author ruoyi
 * @date 2022-02-21
 */
@Api(tags = "APP租客入住记录")
@RestController
@RequestMapping("/app/oar-check-in-records")
public class AppCheckInRecordController extends BaseController {
    @Autowired
    private OarCheckInRecordService oarCheckInRecordService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询租客入住记录列表
     */
    @ApiOperation("查询租客入住记录列表")
    @GetMapping
    public TableDataInfo<OarCheckInRecordDTO> list(OarCheckInRecordQuery oarCheckInRecordQuery) {
        logger.debug("查询租客入住记录列表,查询条件oarCheckInRecordQuery={}", JSONObject.toJSONString(oarCheckInRecordQuery));
        startPage();
        oarCheckInRecordQuery.setFaceVerifiState(1);
//        return oarCheckInRecordService.findAll(oarCheckInRecordQuery);
//        oarCheckInRecordQuery.setUserId(getUserId());+
        return oarCheckInRecordService.selOarRecordAndHouseVoList(oarCheckInRecordQuery);
    }

    /**
     * 导出租客入住记录列表
     */
    @ApiOperation("导出租客入住记录列表")
    @Log(title = "租客入住记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(OarCheckInRecordQuery oarCheckInRecordQuery) {
        logger.debug("查询租客入住记录列表,导出条件oarCheckInRecordQuery={}", JSONObject.toJSONString(oarCheckInRecordQuery));
        oarCheckInRecordQuery.setFaceVerifiState(1);
        List<OarCheckInRecordDTO> list = oarCheckInRecordService.selectOarCheckInRecordList(oarCheckInRecordQuery);
        ExcelUtil<OarCheckInRecordDTO> util = new ExcelUtil<OarCheckInRecordDTO>(OarCheckInRecordDTO.class);
        return util.exportExcel(list, "租客入住记录数据");
    }

    /**
     * 获取租客入住记录详细信息
     */
    @ApiOperation("获取租客入住记录详细信息")
    @GetMapping(value = "/{id}")
    public Response<OarCheckInRecordDTO> getInfo(@PathVariable("id") @ApiParam("租客入住记录ID") String id) {
        logger.debug("获取租客入住记录详细信息,id={}", id);
        checkId(id);
        return Response.success(oarCheckInRecordService.selectOarCheckInRecordById(id).orElseThrow(() -> new ServiceException("无效的ID")));
    }

    /**
     * 新增租客入住记录
     */
    @ApiOperation("新增租客入住记录")
    @PostMapping(value = "instCheckInRecord")
    @RepeatSubmit
    public AjaxResult add(@RequestBody OarCheckInRecordDTO oarCheckInRecordDTO) {
        logger.debug("新增租客入住记录,oarCheckInRecordDTO={}", JSONObject.toJSONString(oarCheckInRecordDTO));
        //String sonwIdKey = RedisConstants.REDIS_CARD_VERIFI_SONW_KEY + oarCheckInRecordDTO.getSonwId();
        //if (!redisCache.exists(sonwIdKey)) {
        //    throw new ServiceException("二维码已失效，请重新扫码填写");
        //}
        String recordId = oarCheckInRecordService.insertOarCheckInRecord(oarCheckInRecordDTO);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("recordId", recordId);


        return AjaxResult.success(resultMap);
    }

    /**
     * 修改租客入住记录
     */
    @ApiOperation("修改租客入住记录")
    @Log(title = "租客入住记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OarCheckInRecordDTO oarCheckInRecordDTO) {
        logger.debug("修改租客入住记录,oarCheckInRecordDTO={}", JSONObject.toJSONString(oarCheckInRecordDTO));
        checkId(oarCheckInRecordDTO.getId());
        return toAjax(oarCheckInRecordService.updateOarCheckInRecord(oarCheckInRecordDTO));
    }

    /**
     * 删除租客入住记录
     */
    @ApiOperation("删除租客入住记录")
    @Log(title = "租客入住记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        logger.debug("删除租客入住记录,ids={}", JSONObject.toJSONString(ids));
        Arrays.asList(ids).forEach(this::checkId);
        return toAjax(oarCheckInRecordService.deleteOarCheckInRecordByIds(ids));
    }

    /**
     * 解析身份信息
     */
    @ApiOperation("解析身份信息")
    @PostMapping(value = "/getIdCardInfo")
    @RepeatSubmit
    public AjaxResult getIdCardInfo(String imgBase64Str, String sonwId) {
        logger.debug("解析身份信息,oarCheckInRecordDTO={}", JSONObject.toJSONString(imgBase64Str));
        if (ToolUtil.isEmpty(sonwId)) {
            throw new ServiceException("sonwId不能为空");
        }
        //String redisKey = RedisConstants.REDIS_CARD_VERIFI_SONW_KEY + sonwId;
        //if (!redisCache.exists(redisKey)) {
        //    throw new ServiceException("二维码已失效，请重新扫码填写");
        //}
        return AjaxResult.success(oarCheckInRecordService.getIdCardInfo(imgBase64Str));
    }

    //@ApiOperation("获取雪花id")
    //@GetMapping(value = "/getSnowflakeId")
    //public AjaxResult getSnowflakeId() {
        //Object snowflakeId = SnowflakeWorker.nextId();
        //redisCache.setCacheObject(RedisConstants.REDIS_CARD_VERIFI_SONW_KEY + snowflakeId, "1", 10, TimeUnit.MINUTES);
        //return AjaxResult.success(snowflakeId);
    //}

    //@ApiOperation("二维码是否失效")
    //@GetMapping(value = "/doesItFail")
    //public AjaxResult doesItFail(String sonwId) {
    //    if (ToolUtil.isEmpty(sonwId)) {
    //        throw new ServiceException("sonwId不能为空");
    //    }
    //    String redisKey = RedisConstants.REDIS_CARD_VERIFI_SONW_KEY + sonwId;
    //    if (!redisCache.exists(redisKey)) {
    //        return AjaxResult.success(0);
    //    }
    //    return AjaxResult.success(1);
    //}

    /**
     * 校验
     *
     * @param id
     */
    private void checkId(String id) {
        Optional.of(id).orElseThrow(() -> new ServiceException("ID不能为空"));
        oarCheckInRecordService.selectOarCheckInRecordById(id).orElseThrow(() -> new ServiceException("无效的ID"));
    }
}
